<template>
  <div class="brand-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>品牌管理</h1>
        </div>

        <el-card>
          <div class="toolbar">
            <el-input
              v-model="keyword"
              placeholder="搜索品牌名称"
              style="max-width: 260px"
              clearable
            />
            <el-button type="primary" @click="filterBrands">搜索</el-button>
            <el-button type="primary" @click="openAdd">新增品牌</el-button>
            <el-button :disabled="!selected.length" @click="batchEnable">批量启用</el-button>
            <el-button :disabled="!selected.length" @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table :data="paginatedBrands" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" prop="brand_id" width="90" />
            <el-table-column label="品牌名称" prop="brand_name" />
            <el-table-column label="品牌Logo" width="120">
              <template #default="{ row }">
                <el-image
                  v-if="row.brand_logo"
                  :src="row.brand_logo"
                  :preview-src-list="[row.brand_logo]"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 4px"
                />
                <span v-else class="text-gray-400">暂无图片</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">{{
                  row.status === 1 ? '启用' : '禁用'
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteBrand(row.brand_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
    <el-dialog
      :title="editing ? '编辑品牌' : '新增品牌'"
      :model-value="dialogVisible"
      width="520px"
      @close="closeDialog"
    >
      <el-form :model="form" label-width="90px">
        <el-form-item label="名称">
          <el-input v-model="form.brand_name" />
        </el-form-item>
        <el-form-item label="品牌Logo">
          <el-upload
            class="logo-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
            :headers="uploadHeaders"
          >
            <img v-if="form.brand_logo" :src="form.brand_logo" class="logo" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { productService } from '@/api'
import type { Brand } from '@/types'
import type { PageResult } from '@/types'

// 扩展Brand类型以包含brand_logo字段
type BrandRow = Brand & { brand_logo?: string }

const loading = ref(false)
const brands = ref<BrandRow[]>([])
const selected = ref<BrandRow[]>([])
const dialogVisible = ref(false)
const editing = ref(false)
const editingId = ref<number | null>(null)
const form = ref<Partial<BrandRow>>({ brand_name: '', brand_logo: '', status: 1 })
// 分页相关状态
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')
const total = ref(0)

// 过滤后的品牌列表
const paginatedBrands = computed(() => {
  return brands.value
})

// 图片上传相关
const uploadUrl = ref('http://localhost:8083/api/v1/upload/image')
const uploadHeaders = ref({
  'Authorization': localStorage.getItem('token') || ''
})

const loadBrands = async () => {
  loading.value = true
  try {
    const res = await productService.getBrandsListPage(page.value, pageSize.value, keyword.value || undefined, undefined)
    const body = res.data as { code: number; data: PageResult<Brand> }
    if (body.code === 200) {
      const data = body.data
      if (data) {
        const baseUrl = 'http://localhost:8083'
        // 处理品牌数据，将相对路径转换为完整URL
        brands.value = (data.list || []).map((brand: Brand) => ({
          ...brand,
          brand_logo: (brand as any).brand_logo && (brand as any).brand_logo.startsWith('/') 
            ? baseUrl + (brand as any).brand_logo 
            : (brand as any).brand_logo
        })) as BrandRow[]
        total.value = data.total || 0
      }
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  } finally {
    loading.value = false
  }
}

const openAdd = () => {
  editing.value = false
  editingId.value = null
  form.value = { brand_name: '', brand_logo: '', status: 1 }
  dialogVisible.value = true
}

const openEdit = async (brand: BrandRow) => {
  editing.value = true
  editingId.value = brand.brand_id
  form.value = { brand_name: brand.brand_name, brand_logo: brand.brand_logo || '', status: brand.status }
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
}

const submit = async () => {
  try {
    if (!form.value.brand_name?.trim()) {
      ElMessage.error('请输入品牌名称')
      return
    }

    if (editing.value && editingId.value) {
      await productService.updateBrand(editingId.value, {
        brand_id: form.value.brand_id,
        brand_name: form.value.brand_name,
        status: form.value.status,
        remarks: form.value.remarks
      })
      ElMessage.success('更新品牌成功')
    } else {
      await productService.addBrand({
        brand_name: form.value.brand_name,
        status: form.value.status,
        remarks: form.value.remarks
      })
      ElMessage.success('添加品牌成功')
    }
    dialogVisible.value = false
    await loadBrands()
  } catch (error) {
    ElMessage.error(editing.value ? '更新品牌失败' : '添加品牌失败')
    console.error('提交品牌失败:', error)
  }
}

const deleteBrand = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个品牌吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await productService.deleteBrand(id)
    ElMessage.success('删除品牌成功')
    await loadBrands()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除品牌失败')
      console.error('删除品牌失败', error)
    }
  }
}

const handleSelectionChange = (rows: BrandRow[]) => {
  selected.value = rows
}

const batchEnable = async () => {
  if (!selected.value.length) return

  try {
    await Promise.all(
      selected.value.map((item) =>
        productService.updateBrand(item.brand_id, {
          brand_name: item.brand_name,
          status: 1,
          remarks: item.remarks || '',
        }),
      ),
    )
    ElMessage.success(`成功启用 ${selected.value.length} 个品牌`)
    selected.value = []
    await loadBrands()
  } catch (error) {
    ElMessage.error('批量启用失败')
    console.error('批量启用失败', error)
  }
}

const batchDisable = async () => {
  if (!selected.value.length) return

  try {
    await Promise.all(
      selected.value.map((item) =>
        productService.updateBrand(item.brand_id, {
          brand_name: item.brand_name,
          status: 0,
          remarks: item.remarks || '',
        }),
      ),
    )
    ElMessage.success(`成功禁用 ${selected.value.length} 个品牌`)
    selected.value = []
    await loadBrands()
  } catch (error) {
    ElMessage.error('批量禁用失败')
    console.error('批量禁用失败', error)
  }
}

const batchDelete = async () => {
  if (!selected.value.length) return

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selected.value.length} 个品牌吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    await Promise.all(selected.value.map((item) => productService.deleteBrand(item.brand_id)))
    ElMessage.success(`成功删除 ${selected.value.length} 个品牌`)
    selected.value = []
    await loadBrands()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('批量删除失败', error)
    }
  }
}

// 图片上传处理方法
const handleLogoSuccess = (response: any) => {
  if (response.code === 200) {
    // 将相对路径转换为完整URL
    const baseUrl = 'http://localhost:8083'
    form.value.brand_logo = baseUrl + response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

const beforeLogoUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 分页处理函数
const filterBrands = () => {
  page.value = 1 // 搜索时重置到第一页
  loadBrands()
}

const handlePageChange = (newPage: number) => {
  page.value = newPage
  loadBrands()
}

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  page.value = 1 // 每页大小改变时重置到第一页
  loadBrands()
}

onMounted(() => {
  loadBrands()
})
</script>

<style scoped>
.brand-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
}
.toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 10px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  
  transition: border-color 0.3s;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.logo {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>
